<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(item, index) in list"
      :key="index"
      @click="$emit('search',item)" 
      icon="search"
    >
    <div slot="title" v-html="reverseStr(item)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSuggestionDate } from "@/api/search";
import lodash from 'lodash'
// lodash.debounce(function() { 要做的事情 }, 时间) ===> 返回还是一个函数
export default {
  name: "SearchSuggestion",
  props: {
    serachText: {
      type: String,
    },
  },
  data() {
    return {
      list: [], //搜索建议
    };
  },
  watch: {
    //   serachText(){}  watch监听数据变化
    serachText: {
      // 监听函数
    //   async handler() { //防抖
    //       if(this.timer) clearTimeout(this.timer)
    //     this.timer = setTimeout(async () => {
    //       let { data } = await getSuggestionDate({
    //         q: this.serachText,
    //       });
    //       console.log(data);
    //       this.list = data.data.options;
    //     },2000);
    //   },
    handler:lodash.debounce(function(value) {
       this.loadSearchSuggestion(value)
    },200),
      deep: false, //是否深监听
      immediate: true, //是否一开始就执行一次
    },
  },
  methods: {
    //   获取搜索建议
      async loadSearchSuggestion(val) {
           let { data } = await getSuggestionDate({
            q: this.serachText,
          });
          console.log(data);
          this.list = data.data.options;
      },
      // 字符串高亮处理
      reverseStr(val) {
       try {
          return val.replaceAll(this.serachText,`<span style="color:red">${this.serachText}</span>`)
       } catch (error) {
         return ''
       }
      }
  },
};
</script>

<style scoped lang="less"></style>
